package net.lab1024.sa.base.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.time.LocalDateTime;

/**
 * mp 插件
 *
 * @Author 1024创新实验室-主任: 卓大
 * @Date 2021-09-02 20:21:10
 * @Wechat zhuoda1024
 * @Email lab1024@163.com
 * @Copyright  <a href="https://1024lab.net">1024创新实验室</a>
 */
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public MybatisPlusInterceptor paginationInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public MetaObjectHandler commonFieldHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                Long currentUserId = 0L;//Optional.of(securityService.getUserId()).orElse(0L);
                this.strictInsertFill(metaObject, "createId", () -> currentUserId , Long.class);
                this.strictInsertFill(metaObject, "updateId", () -> currentUserId, Long.class);
                this.strictInsertFill(metaObject, "createTime", () -> LocalDateTime.now(), LocalDateTime.class);
                this.strictInsertFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class);
                this.strictInsertFill(metaObject, "version", () -> Integer.valueOf(1), Integer.class);
                this.strictInsertFill(metaObject, "deleted", () -> Boolean.valueOf(false), Boolean.class);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                Long currentUserId = 0L;//Optional.of(securityService.getUserId()).orElse(0L);
                this.strictUpdateFill(metaObject, "updateId", () -> currentUserId, Long.class);
                this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class);
            }
        };
    }
}
